<?php

namespace app\admin\controller;

use app\model\GoodsAgency;
use app\model\GoodsAudit;
use app\model\Trademark;
use think\exception\ValidateException;
use app\model\Goods;
use app\model\Category;
use app\model\GoodsDescription;
use app\model\GoodsImage;
use app\model\GoodsSku;
use app\model\GoodsSkuValue;
use app\model\GoodsShareCharges;
use app\model\Store;
use app\model\Config;
use app\model\MemberAuthGroup;
use app\model\GoodsMemberDiscount;
use app\model\Operatingcity;
use app\model\Area;
use PhpOffice\PhpSpreadsheet\IOFactory;
class TrademarkController extends Base
{
    public $model;
    public function __construct(Trademark $model)
    {
        $this->model = $model;
    }

    function index()
	{
		$weid = weid();
		$page = input('post.page', 1, 'intval');
		$keyword = input('post.keyword', '', 'serach_in');
		$cat_id = input('post.cat_id', '', 'serach_in');
		$is_recommand = input('is_recommended');
		$status = input('post.status', '', 'serach_in');
        $where['weid'] = $weid;
        $model  = new Trademark();
		$query = $model->where($where);
		if (!empty($keyword)) {
			$query->where('name', 'like', '%' . $keyword . '%');
		}

		if (!empty($cat_id)) {
			$query->where('cat_id',  $cat_id);
		}

		if (isset($is_recommand) && $is_recommand != '') {
			$query->where('is_recommended', $is_recommand);
		}

		if (isset($status) && $status != "") {
			$query->where(['status' => $status]);
		}

		$res = $query->order('id desc')
			->paginate(getpage())
			->toArray();

		foreach ($res['data'] as &$vo) {
			$vo['image'] = toimg($vo['image']);
			$vo['cat_id'] = Category::getTwoTitle($vo['cat_id']);
			$vo['create_time'] = time_format($vo['create_time']);
			$vo['update_time'] = time_format($vo['update_time']);
		}
		$data['data'] = $res;
		if ($page == 1) {
			$data['field_data']['cidarray'] = _generateSelectTree(Category::getpcarray(3));
		}
		return $this->json($data);
	}

	function listUpdate()
	{
//		$data = only('id,is_recommand,is_additional,status,sort');
		$data = input('post.');
		if (!$data['id']) throw new ValidateException('参数错误');
        $this->model->update($data);
		return $this->json(['msg' => '操作成功']);
	}

	public function update()
	{
		$id = request()->post('id');
		$data = input('post.');
		$data['update_time'] = time();
		$data['image'] = $data['images'][0]['url'];
        $goods_moel  = $this->model;
        if(empty($data['name'])){
            $data['search_type']    = 4;
            $data['zi_num']  = 0;
        }else{
            $arr = $this->checkStringTypeAndLength($data['name']);
            if(!empty($arr)){
                $data['search_type'] = $arr['search_type'];
                $data['zi_num'] = $arr['zi_num'];
            }

        }
		if (empty($id)) {
			$data['weid'] = weid();
			$data['create_time'] = time();

			try {
                $res = $goods_moel->create($data);
                if ($res->id && empty($data['sort'])) {
                    $goods_moel->update(['sort' => $res->id, 'id' => $res->id]);
                }
                $data['id'] = $res->id;
                $this->_synupdata($data);
			} catch (\Exception $e) {
				throw new ValidateException($e->getMessage());
			}
            if($res->id){
                return $this->json(['msg' => '添加成功']);
            }else{
                return $this->json(['msg' => '失败']);
            }

		} else {
			try {
                $goods_moel->update($data);
				$this->_synupdata($data);
			} catch (\Exception $e) {
				throw new ValidateException($e->getMessage());
			}

			return $this->json(['msg' => '修改成功']);
		}
	}

    function checkStringTypeAndLength($str) {
        $length = mb_strlen($str, 'UTF-8'); // 获取字符串长度

        // 判断是否全中文
        if (preg_match('/^[\x{4e00}-\x{9fa5}]+$/u', $str)) {
            return ['search_type'=>1,'zi_num'=>$length]; // 中文
        }

        // 判断是否纯字母
        if (ctype_alpha($str)) {

            return ['search_type'=>2,'zi_num'=>$length]; // 英文
        }

        // 判断是否纯数字
        if (ctype_digit($str)) {
            return ['search_type'=>3,'zi_num'=>$length]; // 数字
        }

        // 判断是否中文+字母
        if (preg_match('/^[\x{4e00}-\x{9fa5}a-zA-Z]+$/u', $str)) {
            return ['search_type'=>5,'zi_num'=>$length]; // 中文+字母
        }
        // 判断是否中文+数字
        if (preg_match('/^[\x{4e00}-\x{9fa5}0-9]+$/u', $str)) {
            return ['search_type'=>6,'zi_num'=>$length]; // 中文+数字
        }
        // 判断是否数字+汉字+字母
        if (preg_match('/^[\x{4e00}-\x{9fa5}a-zA-Z0-9]+$/u', $str)) {
            return ['search_type'=>7,'zi_num'=>$length]; // 数字+汉字+字母
        }
    }

	function _synupdata($data)
	{
		GoodsShareCharges::where('goods_id', $data['id'])->delete();
		if (!empty($data['is_share_charges']) && !empty($data['sharecharges'])) {
			foreach ($data['sharecharges'] as $scvo) {
				if ($scvo['price'] > 0) {
					GoodsShareCharges::create([
						'goods_id' => (int) $data['id'],
						'level' => $scvo['level'],
						'price' => (float) $scvo['price'],
						'charges_method' => (int) $data['charges_method']
					]);
				}
			}
		}
		//图片
		GoodsImage::where('goods_id', $data['id'])->delete();
		if (isset($data['images'])) {
			foreach ($data['images'] as $image) {
				GoodsImage::create([
					'goods_id' => (int) $data['id'],
					'weid' => weid(),
                    'type' => 2,
					'image' => $image['url']
				]);
			}
		}
	}

	function getgoodssku()
	{
		$id =  $this->request->post('id', '', 'serach_in');
		$data['attribute'] = GoodsSku::get_goods_sku($id);
		$data['sourceAttribute'] = $data['attribute'];
		return $this->json(['data' => $data]);
	}

	function getInfo()
	{
		$id =  input('id');
		//if (!$id) throw new ValidateException('参数错误');
        $model =$this->model;
		if ($id) {
			$data = $model->find($id)->toArray();
            $goods_image = GoodsImage::where(['goods_id' => $id,'type'=>2])
                ->field('image')
                ->order('id asc')
                ->select()->toArray();

            if (!empty($goods_image)) {
                foreach ($goods_image as $key => $vo) {
                    $data['images'][$key]['url'] = toimg($vo['image']);
                }
            }
		} else {
			$data = [
				'is_times' => 0,
				'sort' => 100,
				'status' => 1,
			];
		}
		return $this->json(['data' => $data]);
	}

	function delete()
	{
		$idx =  input('id');
		if (!$idx) throw new ValidateException('参数错误');
        $this->model->destroy(['id' => explode(',', $idx)], true);
		return $this->json(['msg' => '操作成功']);
	}
	function getField()
	{
        $data = Category::getpcarray(3);
		$data['cidarray'] = _generateSelectTree($data);
		return $this->json(['data' => $data,'id'=>$this->ocid]);
	}

	public function tongbu(){
        $weid = weid();
        if (empty($this->ocid)) {
            throw new ValidateException('同步失败');
        }
        $ptype      = input('ptype');
        if(!$ptype){
            $ptype = 2;
        }
//        $cate_ids = Operatingcity::where(['id'=>$this->ocid])->value('cate_ids');
        $goods_data = Goods::where(['ptype'=>$ptype,'ocid'=>0])->select();
        $goods_data = $goods_data->toArray();
        if(!$goods_data){
            return $this->json(['msg' => '无数据'.$ptype]);
        }

        foreach ($goods_data as $k=>$v){
            $goods_id = $v['id'];
            unset($v['id']);
            $ocmod           = Operatingcity::find($this->ocid);
            if ($ocmod) {
                $v['province_name'] = $ocmod->province_name;
                $v['city_name']     = $ocmod->city_name;
                $v['district_name'] = $ocmod->district_name;
            }
            $v['ocid']         = $this->ocid;
            $v['audit_status'] = 2;
            $v['ptype']        = $ptype;
            $goods_audit_info = GoodsAudit::where(['name'=>$v['name'],'ocid'=>$this->ocid,'ptype'=>$ptype])->find();
            if($goods_audit_info){
                $v['id'] = $goods_audit_info['id'];
                GoodsAudit::update($v);
                $v['id'] = $goods_audit_info['goods_id'];
                $this->_synupdata($v);
            }else{
                $res = Goods::create($v);
                $v['id'] = $res['id'];
                $this->_synupdata($v);

               $image = GoodsImage::where('goods_id', $goods_id)->select()->toArray();
                if ($image) {
                    foreach ($image as $key=>$val) {
                        GoodsImage::create([
                            'goods_id' => $res['id'],
                            'weid' => weid(),
                            'image' => $val['image']
                        ]);
                    }
                }


                unset($v['id']);
                $v['goods_id']     = $res->id;
                $v['weid']         = $weid;
                $v['create_time']  = time();
                $v['audit_time']   = time();
                $v['update_time']  = time();
                GoodsAudit::create($v);
            }

        }
        return $this->json(['msg' => '同步成功']);
    }

    public function import(){
        $file = request()->file('file');

        $spreadsheet = IOFactory::load($file->getRealPath());
        $sheet = $spreadsheet->getActiveSheet();
        // 处理文件数据
        $data = [];
        $key = -1;
        foreach ($sheet->getRowIterator() as $row) {

            $rowIndex = $row->getRowIndex();
            // 不读取第一行 标题
            if ($rowIndex == 1) {
                continue;
            }
            $cellIterator = $row->getCellIterator();
            $row = [];
            foreach ($cellIterator as $cell) {
                $row[] = $cell->getValue();
            }
            $key +=1;
            $data[$key]['weid']  =  weid();
            $data[$key]['image'] = $row[0]??'';
            $data[$key]['cat_id'] = $row[1]??'';
            $data[$key]['name'] = $row[2]??'';
            $data[$key]['price'] = $data[$key]['original_price'] =  $row[3]??'';
            $data[$key]['brand_id'] = $row[4]??'';
            $data[$key]['tag'] = $row[5]??'';
            $data[$key]['lei_num'] = $row[6]??'';
            $data[$key]['description'] = $row[7]??'';
            $data[$key]['cate_group'] = $row[8]??'';
            $data[$key]['sort'] = $row[9]??'';
            $data[$key]['status'] = 1;
        }
        $this->model->saveAll($data);
        return $this->json(['msg' => '操作成功']);
    }
}
